package mc.contents.web.servlet;

import com.alibaba.fastjson.JSON;
import mc.contents.pojo.view.Rank;
import mc.contents.pojo.view.RankDisplay;
import mc.contents.web.*;
import mc.contents.web.common.AbstractRequestHttpServlet;
import mc.contents.web.common.CommonContext;
import mc.contents.web.common.CommonDisplay;
import mc.contents.web.listener.RankAppAsyncListener;
import mc.contents.web.request.RankCrawRequest;
import mc.contents.web.request.RankPostSender;
import mc.contents.web.result.ReturnResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;

/**
 * Created by LuoHui on 14-11-26.
 */
@WebServlet(name = "rankRequest",urlPatterns="/rank",asyncSupported=true)
public class RankRequestServlet extends AbstractRequestHttpServlet {
    private static final long serialVersionUID = -8033522861152834363L;
    private static Logger log = LoggerFactory.getLogger( RankRequestServlet.class );
    private static final String name = "rank";

    protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        long start = System.currentTimeMillis();
        String nick = request.getParameter("nick");
        String sellerId = request.getParameter("sellerId");
        String keyword = request.getParameter( "keyword" );
        String sortType = request.getParameter( "sortType" );
        String sourceType = request.getParameter( "sourceType" );
        String sessionKey = request.getParameter( "sessionKey" );
        String offset = request.getParameter( "offset" );
        String byApi = request.getParameter( "byApi" );
        String qn = request.getParameter( "qn" );

        paramsNeed( response,nick,sellerId,sessionKey,keyword,sourceType,sortType,offset );
        int limit = Integer.parseInt( offset );

        if( queryBusy(sellerId) ){
            RankDisplay display = new RankDisplay();
            display.setSysBusy(true);
            display.setRanks(new HashSet<Rank>());
            display.setDuration( System.currentTimeMillis() - start );
            String errMsg = "query busy";

            responseFront(200, getJsonStr(display,errMsg), response);
        }else{
            Long id = atomicId.getAndIncrement();
            AsyncContext asyncContext = request.startAsync(request, response);
            asyncContext.setTimeout( crawConfig.getCrawServletTimeOut() );// 总的超时设置为50s
            asyncContext.addListener( new RankAppAsyncListener( id, start, crawService,name ) );//监听器

            CommonContext context = new CommonContext();
            context.setContext( asyncContext );
            RankCrawRequest crawRequest = new RankCrawRequest(keyword,nick,Long.parseLong(sellerId),sessionKey,sourceType,sortType,limit,qn,"true".equals(byApi));
            context.setCrawRequest( crawRequest );
            AsyncContextFactory.put( name, id, context );

            asyncContext.start( new RankPostSender(crawRequest,crawConfig,SourceConfig.getSourceConfig( sourceType ).getConfigName(),id) );
        }
    }

    public String getJsonStr( CommonDisplay display,String errMsg ) {
        ReturnResponse res = new ReturnResponse();
        res.setErrMsg( errMsg );
        res.setResponse( display );
        res.setStatus( 0 );
        return JSON.toJSONString(res);
    }

    private boolean queryBusy(String sellerId) {
        boolean busy = crawService.queryBusy( sellerId );
        if(!busy){
            crawService.writeQueryTime( sellerId );
        }
        return busy;
    }


}
